import { ProColumns, ProTable } from '@ant-design/pro-components';
import { message, Modal } from 'antd';
import React, { PropsWithChildren } from 'react';
import {updateUser} from "@/services/Admin/userManage";
import {USERNAME_UPDATE} from "@/utils/content";

interface UpdateModalProps {
  oldData: Admin.CurrentUser;
  modalVisible: boolean;
  columns: ProColumns<Admin.CurrentUser>[];
  onSubmit: () => void;
  onCancel: () => void;
}

/**
 * 更新数据模态框
 * @param record
 */
const handleUpdate = async (record: Admin.CurrentUser,oldData: Admin.CurrentUser) => {
  const hide = message.loading('正在配置');
  try {
    let params={
      id: record.id,
      username: record.username,
      userAccount: record.userAccount,
      email: record.email,
      userStatus: record.userStatus,
      isAdmin: record.isAdmin,
      updateEnum:''
    };
    if(record.username!==oldData.username){
      params.updateEnum=USERNAME_UPDATE;
    }
    await updateUser(params);
    hide();
    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};

/**
 * 更新数据模态框
 * @param props
 * @constructor
 */
const UpdateModal: React.FC<PropsWithChildren<UpdateModalProps>> = (props) => {
  const { oldData, columns, modalVisible, onSubmit, onCancel } = props;

  return (
    <Modal
      destroyOnClose
      title="更新"
      open={modalVisible}
      onCancel={() => onCancel()}
      footer={null}
    >
      <ProTable<Admin.CurrentUser, Admin.CurrentUser>
        rowKey="id"
        type="form"
        columns={columns}
        form={{
          initialValues: oldData,
        }}
        onSubmit={async (values) => {
          if(values.username==='admin'){
            message.error("admin用户禁止修改");
            return;
          }
          const success = await handleUpdate({
            ...values,
            id: oldData.id,
          },oldData);
          if (success) {
            onSubmit?.();
          }
        }}
      />
    </Modal>
  );
};

export default UpdateModal;
